//
//  RoundViewController.m
//  LiveEducation
//
//  Created by Liu,Qingcan on 2017/4/19.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "RoundViewController.h"
#import "RoundTableViewCell.h"
#import "LiveViewController.h"
//#import "Room+CoreDataClass.h"
#import "VideoModel.h"
#import "Video+CoreDataClass.h"
#import "VideoInfoApi.h"
#import "UpdateRecordApi.h"
#import "UserModel.h"
//#import "User+CoreDataClass.h"
#import "LEUserItem.h"

#import "WatchViewController.h"

@interface RoundViewController ()<UITableViewDelegate,UITableViewDataSource,RoundCellDelegate>
@property(nonnull,nonatomic,strong)UITableView *myTableView;
@property(nonatomic,strong)RoundTableViewCell *roundCell;

@property (nonatomic,assign)CGRect vFrame;
@property (nonatomic,assign)NSInteger roomId;

@end

@implementation RoundViewController


+ (instancetype)initWithSubframe:(CGRect)frame roomId:(NSInteger)roomId{
    return [[self alloc] initWithSubframe:(CGRect)frame roomId:roomId];
}

- (instancetype)initWithSubframe:(CGRect)frame roomId:(NSInteger)roomId{
    self = [super init];
    if (self) {
        
        self.vFrame = frame;
        self.roomId = roomId;
        [self setupDatasWithRoomId:roomId];
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self addSubViews];
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}


#pragma UITableViewDatasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.roundArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    static NSString *iden = @"roundCell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
//    if (cell==nil) {
      RoundTableViewCell*  cell = [RoundTableViewCell cellWithRoundItem:self.roundArray[indexPath.row] tableView:tableView delegate:self];
    cell.selectionStyle = UITableViewCellSeparatorStyleSingleLineEtched;
//        cell = (RoundTableViewCell *)[[RoundTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
//        self.roundCell = cell;
//        self.roundCell.mDelegate = self;
//        self.roundCell.roundItem = self.roundArray[indexPath.row];
//    }
    
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 46;
}


#pragma RoundCellDelegate
- (void)watchButtonSelected:(NSString *)url{
    NSLog(@"watch Button!! %@",url);
    
    //中公教育的   ---  http://zhibo.offcn.com/occchat?cid=30404&map=10_1991_2_190381
    
    //找出用户
    UserModel *userDao = [[UserModel alloc]init];
    NSArray *arr = [userDao selectNumberOfData:0];
    LEUserItem *userItem = arr.firstObject;
    if(userItem == nil || arr.count == 0){
        //            1.提醒用户登录
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意！" message:@"你需要去登录才可以观看喔！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            return ;
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
        return;
        
    }else{
        
        
        
        if (![url hasPrefix:@"http"]) { //rtmp直播
            LiveViewController *watchVC = [LiveViewController initWithLiveUrl:@""];
            watchVC.title = @"直播画面";
            watchVC.view.backgroundColor = [UIColor whiteColor];
            [self.navigationController pushViewController:watchVC animated:YES];
        }else if([url isEqualToString:@"http://19.offcn.comjavascript:;"]){//中公教育的播放
            
        }else{
            WatchViewController *watchVC = [WatchViewController new];
            watchVC.url = url;
            watchVC.roomId = self.roomId;
            [self.navigationController pushViewController:watchVC animated:YES];
            
            
            
        }
        
        
        /////设置为已经被观看了
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *record = [NSString stringWithFormat:@"%@%s",url,"chge"];

        BOOL user_record_status = [defaults boolForKey:record];
        
        if (!user_record_status) {
            
            //2.更新服务器
            UpdateRecordApi *api = [[UpdateRecordApi alloc]initWithUserId:userItem.nid roomId:self.roomId];
            [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                NSDictionary *dict = request.responseJSONObject;
                //2.判断服务器状态码
                NSArray *categories = [NSArray array];
                NSNumber *status = [dict objectForKey:@"statusCode"];
                
                if (status.integerValue == 1) {
                    
                    NSLog(@"更新观看记录-- 成功");
                    //插入观看状态
                    NSString *record = [NSString stringWithFormat:@"%@%s",url,"chge"];
                    [defaults setBool:YES forKey:record];

                    
                    //1.更新本地
                    [defaults setBool:YES forKey:@"user_record"];
                    [defaults synchronize];
                    
                }else{
                    //2.输出状态码
                    NSLog(@"更新观看记录失败 the reason is : %@ ,%s",dict[@"statusMsg"],__FUNCTION__);
                }
                
            } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                
            }];
            
        }
    }
    
   
    
}


#pragma private

- (void)addSubViews{
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.myTableView];
    
}


- (void)setupDatasWithRoomId:(NSInteger) roomId{
//    @property (nonatomic) int16_t id;
//    @property (nullable, nonatomic, copy) NSString *title;
//    @property (nullable, nonatomic, copy) NSString *round_name;
//    @property (nullable, nonatomic, copy) NSString *round_url;
//    @property (nullable, nonatomic, copy) NSString *round_start_time;
//    @property (nullable, nonatomic, copy) NSString *round_status;
//    @property (nonatomic) int16_t video_room_id;
//    @property (nullable, nonatomic, retain) Room *room;
    
    VideoModel *videoDB = [[VideoModel alloc]init];
    self.roundArray = [[videoDB selectVideos:roomId] mutableCopy];
    if (self.roundArray.count == 0) {
        VideoInfoApi *api = [[VideoInfoApi alloc] initWithRoomId:roomId];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            //2.判断服务器状态码
            NSArray *categories = [NSArray array];
            NSNumber *status = [dict objectForKey:@"statusCode"];
            
            if (status.integerValue == 1) {
                categories = dict[@"data"];
            
                //3.success,存数据库
                for(NSDictionary *dc in categories){
                    LEVideoRoom *video = [LEVideoRoom yy_modelWithJSON:dc];
                    [videoDB insertVideoData:video];
                    [_roundArray addObject:video];
                
                }
                
                
                NSLog(@"请求 video 信息 -- 成功");
                [self.myTableView reloadData];
            }else{
                //2.输出状态码
                NSLog(@"未能成功获得数据 the reason is : %@",dict[@"statusMsg"]);
            }

        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }
    
    
    
    
    
    
}




#pragma getter

- (UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc]initWithFrame:self.vFrame];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        
        [_myTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
        _myTableView.backgroundColor = [UIColor whiteColor];
        _myTableView.showsVerticalScrollIndicator = YES;
        _myTableView.showsHorizontalScrollIndicator = NO;
        _myTableView.contentInset = UIEdgeInsetsMake(5, 3, 3, 3);
        
    }
    return _myTableView;
}


- (NSMutableArray*)roundArray{
    if (!_roundArray) {
        _roundArray = [NSMutableArray array];
//        for (int i = 0; i < 10; i++) {
//            RoundItem *item = [[RoundItem alloc]init];
//            item.roundClass = [NSString stringWithFormat:@"第%d讲",i+1];
//            item.roundUrl = @"http://www.baidu.com";
//            item.roundName = @"欢迎来到 lqc 直播平台";
//            item.roundTime = [NSString stringWithFormat:@"2017-06-0%d",i];
//            
//            [_roundArray addObject:item];
////            [_roundArray insertObject:item atIndex:i];
//        }
    }
    return _roundArray;
}

@end
